<template>
    <div class="detail-panel">
        <div v-if="selectedKnowledge" class="edit-form">
            <div class="header-actions">
                <h3 class="form-title">{{ formatFileName(selectedKnowledge) }}</h3>
                <div class="action-buttons" >
                    <template v-if="selectedKnowledge.type === 'page'">
                        <a-button
                            v-if="isReadonly"
                            type="primary"
                            class="edit-btn"
                            @click="isReadonly = false">
                            编辑
                        </a-button>
                        <div v-else>
                            <a-button
                                type="primary"
                                class="edit-btn"
                                @click="handlePublish">
                                发布
                            </a-button>
                            <a-button
                                @click="handleCancelEdit">
                                取消
                            </a-button>
                        </div>
                    </template>
                    <template v-if="selectedKnowledge.type === 'file'">
                        <a-dropdown>
                            <template #overlay>
                                <a-menu @click="downloadFile">
                                    <a-menu-item key="1">导出文件</a-menu-item>
                                    <a-menu-item v-if="parsedContent.ext==='doc' || parsedContent.ext==='docx'" key="2">导出PDF</a-menu-item>
                                </a-menu>
                            </template>
                            <a-button>
                                导出
                                <DownOutlined />
                            </a-button>
                        </a-dropdown>
<!--                        <a-dropdown >-->
<!--                            <template #overlay>-->
<!--                                <a-menu @click="handleMenuClick">-->
<!--                                    <a-menu-item key="download">下载</a-menu-item>-->
<!--                                    <a-menu-item key="export-pdf">导出PDF</a-menu-item>-->
<!--                                    <a-menu-item key="export-word">导出Word</a-menu-item>-->
<!--                                </a-menu>-->
<!--                            </template>-->
<!--                            <a-button class="more-btn">-->
<!--                                更多操作 <DownOutlined />-->
<!--                            </a-button>-->
<!--                        </a-dropdown>-->
                    </template>
                </div>
            </div>
            <div class="markdown-container">
                <template v-if="selectedKnowledge.type === 'file'">
                    <preview-file :selectedKnowledge="selectedKnowledge" >
                    </preview-file>
                </template>
                <template v-else>
                    <RxMarkDown
                        v-model:modelValue="markdownContent"
                        :readonly="isReadonly"
                        :key="selectedKnowledge.id"
                        @valueChange="valueChange"
                    />
                </template>

            </div>
        </div>
        <div v-else class="empty-tip">
            <div class="tip-icon"><FileTextOutlined /></div>
            <div class="tip-text">请选择文件夹里面内容</div>
        </div>
    </div>
</template>

<script setup>
import {ref, defineProps, defineEmits, watch, computed} from 'vue';
import {RxMarkDown} from '@lowcode/jpaas-share-component';
import previewFile from './components/preview-file.vue'
import {TokenUtil} from '@lowcode/jpaas-base-lib'
import knowledgeBaseDetails from "@/common/api/knowledge/knowledgeBaseDetails";
import {message} from "ant-design-vue";

const props = defineProps({
    selectedKnowledge: {
        type: Object,
        default: null,
    },
    knowledgeId:{
        type: String,
        default: "",
    }
});

const emits = defineEmits(['showPageCreation','initData']);

// 新增markdown内容响应式引用
const markdownContent = ref('');
const isReadonly = ref(true)
// 监听知识库内容变化
watch(
    () => props.selectedKnowledge, // 改为监听整个selectedKnowledge对象
    (newVal) => {
        if (newVal) {
            // 强制重新赋值触发编辑器更新
            markdownContent.value = newVal.content || '';
            // 重置编辑状态
            isReadonly.value = newVal.type !== 'page' || true;
        }
    },
    { deep: true,immediate: true }
);

function handleEdit(){
    emits('showPageCreation')
}
const handlePublish = async () => {
    if(!markdownContent.value){
        return message.error("当前未获得markdown文本内容!")
    }
    const params = {
        name:props.selectedKnowledge.name,
        content:markdownContent.value ,
        pkId:props.selectedKnowledge.id,
    }
    let result = await knowledgeBaseDetails.updateByText(params);
    if(result.success){
        isReadonly.value = true;
        emits('initData')
    }
};
const valueChange = async (value) => {
    markdownContent.value = value;
};
// 新增名称格式化方法
const formatFileName = (dataRef) => {
    let name = dataRef.name || '';
    if(dataRef.type !== 'file'){
        return name
    }else{
        // 移除扩展名（仅对文件类型）
        const lastDotIndex = name.lastIndexOf('.');
        if (lastDotIndex > 0) {
            name = name.substring(0, lastDotIndex);
        }
        // 处理以点结尾的情况（仅当文件名以点结尾时）
        return name.endsWith('.') ? name.slice(0, -1) : name;
    }
};
// 修改取消按钮处理
const handleCancelEdit = () => {
    isReadonly.value = true;
    // 重置为原始内容
    markdownContent.value = props.selectedKnowledge.content || '';
};
// 新增导出处理方法
// const handleMenuClick = ({ key }) => {
//     switch(key) {
//         case 'download':
//             downloadFile(props.selectedKnowledge);
//             break;
//     }
// };
/**
 * 下载文件
 */
const parsedContent = computed(() => {
    try {
        if (typeof props.selectedKnowledge.content === 'string') {
            return JSON.parse(props.selectedKnowledge.content);
        }
        return props.selectedKnowledge.content;
    } catch (e) {
        console.error('解析内容失败:', e);
        return null;
    }
});
const downloadFile = (e)=>{
    let token=TokenUtil.getToken();
    let fileId = parsedContent.value.fileId;
    //是否转换pdf
    let transPdf = false;
    if (e.key === "2"){
        transPdf = true;
    }
    if(fileId){
        let url = `/api/api-system/system/core/sysFile/download/${fileId}?accessToken=` + token + `&transPdf=` + transPdf;
        let a = document.createElement('a');
        a.href = url;
        a.style.display = 'none';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    }else{
        message.error('当前没有文件ID');
    }
}

</script>

<style scoped lang="scss">
.detail-panel {
    flex: 1;
    background: white;
    border-radius: 8px;
    padding: 16px;

    .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
    }

    .header-actions {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;

        .action-buttons {
            display: flex;
            gap: 12px;

            .edit-btn {
                background-color: #1890ff;
                border-color: #1890ff;
                margin: 0 10px;
            }

            .more-btn {
                &:hover, &:focus {
                    color: #1890ff;
                    border-color: #1890ff;
                }
            }
        }
    }

    .form-title {
        margin: 0 0 0 10px;
        font-size: 20px;
        font-weight: bold;
    }

    .edit-form {
        max-width: 100%;
        height: 100%;
    }

    .empty-tip {
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: #999;

        .tip-icon {
            font-size: 48px;
            margin-bottom: 16px;
        }

        .tip-text {
            font-size: 14px;
        }
    }

    .markdown-container {
        height: calc(100vh - 275px);
        position: relative;

        :deep(.v-note-wrapper) {
            height: 98.5%;
            overflow-y: auto;
            box-shadow: none;
            display: flex;
            flex-direction: column;
            z-index:50;
        }
    }

    .more-btn {
        border: 1px solid #d9d9d9;
        background-color: #fff;
        color: #595959;
    }
}
</style>
